var express = require('express');
var router = express.Router();
const multer = require('multer');
const fs = require('fs');
const {zzshequModel}=require('../model/models')
const upload = multer({ dest: 'uploads/' });
router.post('/upload', upload.single('file'), (req, res) => {
  // 获取文件信息
  const file = req.file;
  // 获取切片文件名称
  let filename = req.body.filename
  // 去掉文件名后缀
  filename = filename.slice(0,filename.length - 4)
  // 获取切片文件索引值
  const index = req.body.index;
  // 配置切片文件的路径 uploads/文件名
  const chunkDir = `uploads/${filename}`;
  // 判断切片文件路径是否存在，不存在进行创建文件夹
  if (!fs.existsSync(chunkDir)) {
    fs.mkdirSync(chunkDir);
  }
  // 配置切片文件路径文件夹下的索引文件   uploads/文件名/0
  const chunkPath = `${chunkDir}` + '/' + `${index}`;
  // 将文件移动到 切片文件路径
  fs.renameSync(file.path,chunkPath);

  res.send('Chunk uploaded successfully');
});
router.post('/merge', (req, res) => {
  // 获取文件名称
  let { filename } = req.body;
  filename = filename.slice(0, filename.length - 4)
  // 视频文件夹路径
  const chunkDir = `uploads/${filename}`;
  // 视频合成完的路径
  const filePath = `uploads/${filename}.mp4`;
  // 读取文件夹中的所有索引的切片文件 并排序
  const chunks = fs.readdirSync(chunkDir);
  chunks.sort((a, b) => a - b);
  // 遍历切片文件 
  chunks.forEach((chunk, index) => {
    // 获取切片文件夹下的切片文件路径
    const chunkPath = `${chunkDir}/${chunk}`;
    // 将切片文件追加到 新文件 末尾
    fs.appendFileSync(filePath, fs.readFileSync(chunkPath));
    // 删除切片文件路径
    fs.unlinkSync(chunkPath);
  });
  // 删除文件夹
  fs.rmdirSync(chunkDir);
  res.send('File merged successfully');
});
module.exports = router;
